package com.source.lightfowl.person.service.impl;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.google.zxing.common.BitMatrix;
import com.source.lightfowl.VO.PersonVO;
import com.source.lightfowl.constant.ImageCatalogue;
import com.source.lightfowl.constant.SessionKey;
import com.source.lightfowl.handler.MyException;
import com.source.lightfowl.person.dao.PersonDao;
import com.source.lightfowl.person.entity.*;
import com.source.lightfowl.person.service.*;
import com.source.lightfowl.utils.*;
import org.hibernate.annotations.CreationTimestamp;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class PersonServiceImpl implements PersonService {

//    @Autowired
//    private Person person;
    @Autowired
    private PersonDao personDao;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RolePlateService rolePlateService;
    @Autowired
    private UrlService urlService;
    @Autowired
    private PlateService plateService;
    @Autowired
    private DateUtils dateUtils;
    @Autowired
    private IMailService iMailService;
    @Autowired
    private RandomNumberUtils randomNumberUtils;
    @Value("${person.salt}")
    private String salt;

    @Override
    public MyResult register(String username, String password, String email, HttpServletRequest request, String clientCode) {
        HttpSession session = request.getSession();
        String serverCode = (String) session.getAttribute(email);
        if(serverCode==null /*&& clientCode.equals("")*/){
            return MyResult.build(0,"验证码失效");
        }else {

            if(serverCode.equals(clientCode)/*clientCode.equals("true")*/){

                /*
                int i = personDao.register(username, password.getBytes(),
                        salt, email, dateUtils.getDate());
                 */
                int i = personDao.register(UUIDUtils.getUUID(), username, password.getBytes(),
                        salt, email, dateUtils.getDate());
                if(i==1){
                    session.removeAttribute(email);
                    return MyResult.build(1,"成功");
                }else {
                    return MyResult.build(0,"失败");
                }
            }else {
                return MyResult.build(0,"验证码错误");
            }
        }
    }

    @Override
    public MyResult register(Person person, HttpServletRequest request, String clientCode,  MultipartFile file) {
        String username = person.getLoginName();
        String email = person.getEmail();
        String password = person.getPassword().toString();
        HttpSession session = request.getSession();
        String serverCode = (String) session.getAttribute(email);
        if(serverCode==null /*&& clientCode.equals("")*/){
            return MyResult.build(0,"验证码失效");
        }else {

            if(serverCode.equals(clientCode)/*clientCode.equals("true")*/){
                if (file != null){
                    String s = null;
                    String decode = null;
                    try {//解析二维码
                        decode = QRCodeUtil.decode(ImageUtil.multipartFileToFile(file));
                    } catch (Exception e) {
                        throw new MyException(StatusCode.ANALYSE_IMG_ERROR, "二维码图片解析失败");
                    }
                    person.setWechatCodeDecode(decode);
                    try {
                        s = ImageUtil.saveImage(file, ImageCatalogue.User_Catalogue);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    person.setWechatCode(s);
                }else {
                    //自动给没有上传二维码的用户生成唯一标识的二维码
                    String code = UUIDUtils.getUUID22();
                    person.setWechatCodeDecode(code);
                    String fileName = UUIDUtils.getUUID() + ".jpg";
                    String destPath = ImageUtil.IMAGE_PATH + ImageCatalogue.User_Catalogue + File.separator + fileName;
                    String relativePath = "image" + File.separator + ImageCatalogue.User_Catalogue + File.separator+ fileName;
                    System.out.println(relativePath);
                    try {
                        QRCodeUtil.encode(code, destPath);
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new MyException();
                    }
                    System.out.println("aaaaaaaaaaa");
                    person.setWechatCode(relativePath);
                }
                /*
                int i = personDao.register(username, password.getBytes(),
                        salt, email, dateUtils.getDate());
                 */
                int i = personDao.register2(UUIDUtils.getUUID(), username, password.getBytes(),
                        salt, email, dateUtils.getDate(), person.getWechatCode(), person.getWechatCodeDecode());
                if(i==1){
                    session.removeAttribute(email);
                    return MyResult.build(1,"成功");
                }else {
                    return MyResult.build(0,"失败");
                }
            }else {
                return MyResult.build(0,"验证码错误");
            }
        }
    }

    @Override
    public MyResult updatePassword(String password, String email, HttpServletRequest request, String clientCode) {
        HttpSession session = request.getSession();
        String serverCode = (String) session.getAttribute(email);
        if(serverCode==null){
            return MyResult.build(0,"验证码失效");
        }else {
            if(serverCode.equals(clientCode)){
                int i = personDao.updatePassword(password.getBytes(),
                        salt, email, dateUtils.getDate());
                if(i==1){
                    session.removeAttribute(email);
                    return MyResult.build(1,"成功");
                }else {
                    return MyResult.build(0,"失败");
                }
            }else {
                return MyResult.build(0,"验证码错误");
            }
        }
    }

    @Override
    public MyResult login(String username, String password, HttpServletRequest request) {
        Person user = personDao.login(username, password.getBytes(), salt);
        if (user!=null){
            if (null == user.getRole() || "".equals(user.getRole()))
                return MyResult.build(StatusCode.FORBIDDEN,"未赋予角色，无权登录");
            HttpSession session = request.getSession();
            session.setAttribute(SessionKey.USER, user);
            List<PlateExtends> plateExtendsList= new ArrayList<PlateExtends>();
            //List<Url> urlList = new ArrayList<>();

            //逗号分隔的字符串转换为数组
            //获得用户所分配到的角色id
            //String[] strArray = user.getRid().split(",");//拿到rid（用户能操作的角色字符串）转化为数组
            //for(String s : strArray) {
            String rid = user.getRole();
            //获取用户所拥有的访问路径
            List<Url> urlList = urlService.findUrlsByRid(rid);
            //System.out.println(urls);
            /*for (Url url : urls) {

                //打印看看是否成功
                System.out.println(url.getUrlname());

                urlList.add(url);
            }*/
            //获得用户所拥有的访问板块
            List<Plate> plateList = plateService.querryPlate(rid);
            for (int i = 0; i < plateList.size(); i++) {
                PlateExtends plateExtends = new PlateExtends();

                //打印看看是否成功
                System.out.println(plateList.get(i).getPname());

                plateExtends.setPlates(plateList.get(i));
                //获取用户所拥有的板块的操作
                List<Role_Plate> role_platelist = rolePlateService.querryRolePlateByPtype(plateList.get(i).getPtype(), plateList.get(i).getBigpid(), rid);
                String[] eids = new String[role_platelist.size()];
                for(int j = 0; j < role_platelist.size(); j++){
                    String eid = role_platelist.get(j).getEids();
                    eids[j] = eid;
                    System.out.println(eid);
                }
                plateExtends.setEids(eids);
                plateExtendsList.add(plateExtends);
            }
            //}
            //通过静态工厂创建UsersExtends对象
            UsersExtends usersExtends = new UsersExtends();
            //角色拥有的路径权限
            usersExtends.setUrls(urlList);
            //角色拥有的子模块权限
            usersExtends.setPlateExtendsList(plateExtendsList);
            //浅拷贝

//            PersonVO usercopy = new PersonVO(user.getId(), user.getLoginName(), user.getPassword(), user.getName(), user.getEmail(), user.getPhone(), user.getMobile(), user.getSex(), user.getQq(), user.getWechat(), user.getWechatCode(), user.getWechatCodeDecode(), user.getIdCard());
            PersonVO usercopy = new PersonVO();
            BeanUtils.copyProperties(user, usercopy);
            //设置角色名
            Role role = roleService.querryUserPower(user.getRole());
            if (null == role || "".equals(role.getRname())) {
                session.removeAttribute(SessionKey.USER);
                return MyResult.build(StatusCode.FORBIDDEN,"角色关联信息无效");
            }
            String roleName = role.getRname();
            usercopy.setRoleName(roleName);
            //加入Users对象
            usersExtends.setUser(usercopy);

            //放入session
            session.setAttribute(SessionKey.USERSEXTENDS_SESSION_KEY, usersExtends);
//            String s=(String)request.getSession().getAttribute(username);
//            session.setAttribute("username", username);

            //需要权限控制的全部路径
//            session.setAttribute("allUrls", urlService.finAllUrls());
            return MyResult.build(1,"登录成功", usersExtends);
        }else{
            System.out.println("用户名或密码为空");
            return MyResult.build(0,"账户或密码错误");
        }

        /*Person person = personDao.login(username, password.getBytes(), salt);
        if(person!=null){
            HttpSession session = request.getSession();
            session.setAttribute("person",person);
            return MyResult.build(1,"登录成功");
        }else {
            return MyResult.build(0,"账户或密码错误");
        }*/
    }

    @Override
    public MyResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object user = session.getAttribute(SessionKey.USERSEXTENDS_SESSION_KEY);
        if(user!=null){
            session.removeAttribute(SessionKey.USERSEXTENDS_SESSION_KEY);
            session.removeAttribute(SessionKey.USER);
            return MyResult.build(1,"注销成功");
        }else {
            return MyResult.build(1,"此用户已经注销");
        }
    }

    @Override
    public MyResult sendMail(String email, HttpServletRequest request) {
        String content = randomNumberUtils.getFiveRandom();
        String subject = "邮箱验证";
        iMailService.sendSimpleMail(email,subject,content);
        HttpSession session = request.getSession();
        session.setAttribute(email,content);
        session.setMaxInactiveInterval(60);
        return MyResult.build(1,"验证码已发送");
    }

    @Override
    public MyResult checkUsername(String username) {
        Person person = personDao.checkUsername(username);
        if(person!=null){
            return MyResult.build(1,"该用户名已被注册");
        }else {
            return MyResult.build(0,"");
        }
    }

    @Override
    public MyResult checkEmail(String email) {
        List<Person> person = personDao.checkEmail(email);
        if(person.size() !=0){
            return MyResult.build(1,"该邮箱已被注册");
        }else {
            return MyResult.build(0,"");
        }
    }


}
